//
//  AyStatusCacheTool.m
//  xWeibo
//
//  Created by alvis mac on 11/5/15.
//  Copyright © 2015 alvis. All rights reserved.
//

#import "AyStatusCacheTool.h"
#import "AyAccount.h"
#import "AyAccountTool.h"
#import "FMDB.h"

@implementation AyStatusCacheTool

static FMDatabaseQueue *_queue;

+ (void) setup{
    NSString *path=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"statuses.sqlite"];
    _queue=[FMDatabaseQueue databaseQueueWithPath:path];
    
    [_queue inDatabase:^(FMDatabase *db) {
         [db executeUpdate:@"create table if not exists t_status (id integer primary key autoincrement, access_token text, idstr text, status blob);"];
    }];
}


+ (void) addStatuses:(NSArray *)statusArray{
    for (AyStatus * status in statusArray) {
        [self addStatus:status];
    }
}

+ (void) addStatus:(AyStatus *) status{
    [self setup];
    [_queue inDatabase:^(FMDatabase *db) {
        NSString *accessToken = [AyAccountTool account].access_token;
        NSString *idstr = status.idstr;
        NSData *data=[NSKeyedArchiver archivedDataWithRootObject:status];
        [db executeUpdate:@"insert into t_status (access_token, idstr, status) values(?, ? , ?)", accessToken, idstr, data];
    }];
     [_queue close];
}



+ (NSArray *) statuesWithParam:(AyHomeStatusesParame *) param{
    [self setup];
    __block NSMutableArray *statusArray=nil;
    
    [_queue inDatabase:^(FMDatabase *db) {
        statusArray=[NSMutableArray array];
        NSString *accessToken = [AyAccountTool account].access_token;
        
        FMResultSet *rs = nil;
        if (param.since_id) { // 如果有since_id
            rs = [db executeQuery:@"select * from t_status where access_token = ? and idstr > ? order by idstr desc limit 0,?;", accessToken, param.since_id, param.count];
        } else if (param.max_id) { // 如果有max_id
            rs = [db executeQuery:@"select * from t_status where access_token = ? and idstr <= ? order by idstr desc limit 0,?;", accessToken, param.max_id, param.count];
        } else { // 如果没有since_id和max_id
            rs = [db executeQuery:@"select * from t_status where access_token = ? order by idstr desc limit 0,?;", accessToken, param.count];
        }
        
        while (rs.next) {
            NSData *data=[rs dataForColumn:@"status"];
            AyStatus *status=[NSKeyedUnarchiver unarchiveObjectWithData:data];
            [statusArray addObject:status];
        }
        
    }];
    [_queue close];
    return statusArray;
}



@end
